package org.xiaov.core.net;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xiaov.bean.date.RegexPool;
import org.xiaov.execption.XiaovUtilsException;

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * <p>
 *
 * </p>
 *
 * @author xiaovcloud
 * @since 2021/7/17 14:11
 */
public class NetHelper {
	private static final Logger log = LoggerFactory.getLogger(NetHelper.class);

	/**
	 * 根据ip地址(xxx.xxx.xxx.xxx)计算出long型的数据
	 *
	 * @param strIP IP V4 地址
	 * @return long值
	 */
	public static long ipv4ToLong(String strIP) {
		//Validator.validateIpv4(strIP, "Invalid IPv4 address!");
		if (!Pattern.matches(RegexPool.IPV4, strIP)) {
			throw new XiaovUtilsException("ipv4地址输入错误，输入地址为：" + strIP);
		}
		final long[] ip = {};
		return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];
	}

	/**
	 * 获取mac地址的方法
	 *
	 * @param inetAddress InetAddress对象
	 * @return mac地址
	 * @throws SocketException .
	 */
	public static String getLocalMac(InetAddress inetAddress) throws SocketException {
		byte[] mac = NetworkInterface.getByInetAddress(inetAddress).getHardwareAddress();
		StringBuilder sb = new StringBuilder("0");
		for (int i = 0; i < mac.length; i++) {
			if (i != 0) {
				sb.append("-");
			}
			int temp = mac[i] & 0xff;
			String str = Integer.toHexString(temp);
			sb.append(str);
		}
		return sb.toString().toUpperCase();
	}

	/**
	 * 获取本机IP地址的方法
	 *
	 * @return ip地址
	 */
	public static String getIPv4() {
		try {
			return InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
			e.printStackTrace();
			throw new XiaovUtilsException(e.getMessage());
		}
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 *
	 * @param url   发送请求的 URL
	 * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		StringBuilder result = new StringBuilder();
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());

			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result.append(line);
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		//使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result.toString();
	}

	/**
	 * 向指定URL发送GET方法的请求
	 *
	 * @param url   发送请求的URL
	 * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static String sendGet(String url, String param) {
		StringBuilder result = new StringBuilder();
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setConnectTimeout(30000);
			connection.setReadTimeout(30000);
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.out.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					connection.getInputStream(), StandardCharsets.UTF_8));
			String line;
			while ((line = in.readLine()) != null) {
				result.append(line);
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result.toString();
	}

	/**
	 * put请求，body的方法，获取结果
	 *
	 * @param url  请求地址
	 * @param json 请求参数
	 * @return 返回结果
	 */
	public static String sentPut(String url, Object json) {
		String result = "";
		try {
			URL restURL = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) restURL.openConnection();
			connection.setRequestMethod("PUT");
			connection.setDoInput(true);
			connection.setDoOutput(true);
			//消息请求头Headers
			Map<String, String> headersMap = new HashMap<String, String>();
			headersMap.put("Content-Type", "application/json; charset=utf-8");
			//循环增加header
			for (Map.Entry<String, String> elem : headersMap.entrySet()) {
				connection.setRequestProperty(elem.getKey(), elem.getValue());
			}
			OutputStreamWriter outer = null;
			outer = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
			outer.write(json.toString());
			outer.flush();
			outer.close();
			InputStream ips = connection.getInputStream();

			BufferedReader in = new BufferedReader(new InputStreamReader(ips, StandardCharsets.UTF_8));
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while ((line = in.readLine()) != null) {
				buffer.append(line);
				buffer.append("\r\n");
			}
			in.close();
			ips.close();
			connection.disconnect();
			//得到结果
			result = buffer.toString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}


}
